import gradio as gr
import requests

# 配置 DeepSeek API
API_URL = "https://api.deepseek.com/v1/chat/completions"
API_KEY = "sk-b6ff7747cf4a440682633b89db854274"  # 替换为你的 DeepSeek API 密钥

# 调用 DeepSeek API 的函数
def chat_with_deepseek(user_input, history):
    headers = {
        "Authorization": f"Bearer {API_KEY}",
        "Content-Type": "application/json"
    }

    # 构造聊天历史
    messages = [{"role": "system", "content": "You are an AI assistant."}]
    for user_msg, bot_msg in history:
        messages.append({"role": "user", "content": user_msg})
        messages.append({"role": "assistant", "content": bot_msg})
    messages.append({"role": "user", "content": user_input})

    data = {
        "model": "deepseek-chat",  # 或 deepseek-coder 视需求而定
        "messages": messages
    }

    response = requests.post(API_URL, headers=headers, json=data)
    if response.status_code == 200:
        bot_reply = response.json()["choices"][0]["message"]["content"]
        return bot_reply
    else:
        return f"Error: {response.status_code}, {response.text}"

# 创建 Gradio 界面
chatbot = gr.ChatInterface(chat_with_deepseek, title="DeepSeek AI Chatbot")

# 启动应用
if __name__ == "__main__":
    chatbot.launch()